package oylj.recycle.all_in_one;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

public class Utils {
    private static final String TAG = "MyUtils";
    public static String createInnerImg(Context context){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.getDefault());
        String time = format.format(new Date());
        return Objects.requireNonNull(context.getExternalFilesDir(null)).getAbsolutePath()+"/"+ time.replace(":","-").replace(" ", "_") +
                ".jpg";
    }
    public static String saveBitmap(Context context,Bitmap bitmap){
        String filename = createInnerImg(context);
        File imageFile = new File(filename);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imageFile);
            // 将Bitmap压缩为PNG格式，100表示压缩质量
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return filename;
            // 返回文件的绝对路径
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void deleteJpgFiles(Context context) {
        // 获取应用的外部存储目录
        File directory = context.getExternalFilesDir(null);

        if (directory != null && directory.isDirectory()) {
            // 获取目录下所有文件
            File[] files = directory.listFiles();

            if (files != null) {
                for (File file : files) {
                    // 检查文件是否以 .jpg 结尾
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".jpg")) {
                        boolean deleted = file.delete();
                        if (deleted) {
                            Log.d(TAG, file.getName() + " deleted successfully.");
                        } else {
                            Log.d(TAG, "Failed to delete " + file.getName());
                        }
                    }
                }
            }
        }
    }

    public static String bitmapToBase64(Bitmap bitmap) {
        // 创建一个输出流，用于将 Bitmap 压缩为字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        // 压缩 Bitmap 为 PNG 格式字节数组
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

        // 获取字节数组
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        // 使用 Base64 编码字节数组，并返回编码后的字符串
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
    public static String compressImgToBase64(String fileName,int sizeMB){
        Bitmap bitmap = BitmapFactory.decodeFile(fileName);
        if (bitmap == null) {
            return null;
        }


        // 2. 设置初始压缩质量
        int quality = 90; // 初始质量(0-100)
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Log.d(TAG, "compressImgToBitmap: fileName "+fileName);
        // 3. 循环压缩直到大小合适
        do {
            outputStream.reset(); // 清空输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            Log.d(TAG, "compressImgToBitmap: outputStream.size() "+outputStream.size() );
            quality =(int)(quality * 0.9); // 每次降低10%质量
            if (outputStream.size() <= 1024 * 1024 * sizeMB) {
                // 转换为Base64字符串
                String base64 =  Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
                return  base64.trim();
            }
        } while (quality > 0);
        return "";
    }
    public static String compressBitmapToBase64(Bitmap bitmap, double sizeMB){
        if (bitmap == null) {
            return null;
        }


        // 2. 设置初始压缩质量
        int quality = 90; // 初始质量(0-100)
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 3. 循环压缩直到大小合适
        do {
            outputStream.reset(); // 清空输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            quality =(int)(quality * 0.9); // 每次降低10%质量
            if (outputStream.size() <= 1024 * 1024 * sizeMB) {
                // 转换为Base64字符串
                return  Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP).trim();

            }
        } while (quality > 0);
        return "";
    }
}
